#!/usr/bin/env python
import subprocess
import py_trees
import py_trees.console as console


def create_tree(level: str) -> py_trees.behaviour.Behaviour:
    """
    Create the root behaviour and it's subtree.
    Returns:
        the root behaviour
    """
    root = py_trees.composites.Selector(name="Demo Dot Graphs %s" % level, memory=False)
    first_blackbox = py_trees.composites.Sequence(name="BlackBox 1", memory=True)
    first_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    first_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    first_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    first_blackbox.blackbox_level = py_trees.common.BlackBoxLevel.BIG_PICTURE
    second_blackbox = py_trees.composites.Sequence(name="Blackbox 2", memory=True)
    second_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    second_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    second_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    second_blackbox.blackbox_level = py_trees.common.BlackBoxLevel.COMPONENT
    third_blackbox = py_trees.composites.Sequence(name="Blackbox 3", memory=True)
    third_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    third_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    third_blackbox.add_child(py_trees.behaviours.Running("Worker"))
    third_blackbox.blackbox_level = py_trees.common.BlackBoxLevel.DETAIL
    root.add_child(first_blackbox)
    root.add_child(second_blackbox)
    first_blackbox.add_child(third_blackbox)
    return root


##############################################################################
# Main
##############################################################################
def choose_dot_graphs_level() -> str:
    level_list = ["all", "fine_detail", "detail", "component", "big_picture"]
    idx = 0
    help_str = ""
    for level in level_list:
        help_str += f"{idx}: {level}\n"
        idx += 1
    dot_graphs_level = int(input(f"请输入序号选择level: \n{help_str}"))
    return level_list[dot_graphs_level]


def main() -> None:
    """Entry point for the demo script."""
    py_trees.logging.level = py_trees.logging.Level.DEBUG
    dot_graphs_level = choose_dot_graphs_level()
    enum_level = py_trees.common.string_to_visibility_level(dot_graphs_level)
    root = create_tree(dot_graphs_level)
    py_trees.display.render_dot_tree(root, enum_level)

    if py_trees.utilities.which("xdot"):
        try:
            subprocess.call(["xdot", "demo_dot_graphs_%s.dot" % dot_graphs_level])
        except KeyboardInterrupt:
            pass
    else:
        print("")
        console.logerror("No xdot viewer found, skipping display [hint: sudo apt install xdot]")
        print("")


if __name__ == "__main__":
    main()
